package com.mxdx.edu.common;

import java.util.Map;

public class CommonUtils {
	
	
	/**
	 * 获取验证码（6位）
	 * @return
	 */
	public static String generateCode(int len) {
		return String.valueOf(Math.random()).substring(2, 2 + len);
	}
	
	/**
	 * 从map中获取值，如果为null ，返回defaultValue
	 * @param map
	 * @param key
	 * @param defalutValue
	 * @return
	 */
	public static String getValueFromMap(Map<String, String> map, String key, String defalutValue) {
		String tmp = map.get(key);
		if(tmp == null) return defalutValue;
		return tmp.trim();
	}
	
	public static String getStrValueFromMap(Map<String, Object> map, String key, String defalutValue) {
		Object tmp = map.get(key);
		if(tmp == null){
			return defalutValue;
		}
		if(tmp instanceof  String) {
			return (String) tmp;
		}
		return String.valueOf(tmp);
	}
	
	/**
	 * 从map中获取long型数据
	 * @param map
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public static long getLongValueFromMap(Map<String, Object> map, String key, long defaultValue) {
		Object tmp = map.get(key);
		if(tmp == null) return defaultValue;
		if(tmp instanceof Integer) return (Integer)tmp;
		if(tmp instanceof Long) return (Integer)tmp;
		
		return defaultValue;
	}
	
	public static int getIntegerValueFromMap(Map<String, Object> map, String key, Integer defaultValue) {
		Object tmp = map.get(key);
		if(tmp == null) return defaultValue;
		if(tmp instanceof Integer) return (Integer)tmp;
		if(tmp instanceof Long) return (Integer)tmp;
		return defaultValue;
	}
	
	public static int getIntegerFromStrMap(Map<String, String> map, String key, Integer defaultValue) {
        String tmp = map.get(key);
        if(tmp == null) return defaultValue;
        try{
            return Integer.parseInt(tmp);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return defaultValue;
    }
	
}
